import { downloadFileApi } from '@/api/escloud/upload';
import { createImgPreview } from '@/components/Preview';
import { useMessage } from '@/hooks/web/useMessage';
import { getAppEnvConfig } from '../env';
import { getJti } from '@/utils/cookie';
import axios from 'axios';

const { createMessage } = useMessage();
// 下载文件
export function downloadFile(obj: any, fileName: string) {
  const url = window.URL.createObjectURL(new Blob([obj.data]));
  const link = document.createElement('a');
  link.style.display = 'none';
  link.href = url;
  link.download = fileName || obj.fileName;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

// 复制内容到剪切板
export function handleTextCopy(text: string) {
  // 复制内容到剪切板
  if (text) {
    const input = document.createElement('input');
    document.body.appendChild(input);
    input.value = text; // 此处为需要复制的文本变量
    input.focus();
    input.select();
    try {
      const result = document.execCommand('copy');
      document.body.removeChild(input);
      if (!result) {
        // console.error('复制失败');
        createMessage.error('内容已复制到剪贴板');
      } else {
        createMessage.success('复制成功');
      }
    } catch (e) {
      document.body.removeChild(input);
      createMessage.error('当前浏览器不支持复制功能，请检查更新或更换其他浏览器操作');
    }
  } else {
    createMessage.error('无内容可复制！');
  }
}

// 获取文件类型
export function getFileType(fileName: string) {
  let fileType = fileName ? fileName.split('.')[fileName.split('.').length - 1] : '';
  fileType = fileType ? fileType.toLowerCase() : '';
  // 获取文件类型
  let type = 'other';

  if (fileType.includes('doc') || fileType.includes('docx')) {
    type = 'word';
  } else if (fileType.includes('xls') || fileType.includes('xlsx')) {
    type = 'excel';
  } else if (fileType.includes('pdf')) {
    type = 'pdf';
  } else if (fileType.includes('jpg') || fileType.includes('png') || fileType.includes('jpeg')) {
    type = 'image';
  }

  return type;
}

// 拼接附件url
export function getFileUrl({ source, bucketName, path }) {
  const { VITE_GLOB_IMG_DOMAIN } = getAppEnvConfig();
  return `${VITE_GLOB_IMG_DOMAIN}/${source}/${bucketName}/${path}`;
}

// 预览文件
export async function previewFile(fileName: string, fileUrl: string, Authorization: Boolean) {
  let newFileUrl = '';
  const fileType = getFileType(fileName);
  const { VITE_GLOB_SUB_DOMAIN } = getAppEnvConfig();
  // 把minio的域名换成img域名
  fileUrl = fileUrl.replace(`minio${VITE_GLOB_SUB_DOMAIN}`, `img${VITE_GLOB_SUB_DOMAIN}/MINIO`);
  console.log('Authorization------Authorization', Authorization, fileName, fileUrl, fileType);
  if (Authorization) {
    const token = getJti();
    console.log('fetchFiles-url', fileUrl);
    const res = await axios.get(`${fileUrl}?isAdmin=true`, {
      headers: {
        Authorization: `jti_${token}`,
      },
      responseType: 'blob',
    });
    console.log('fetchFiles-res=========================-----------------', res);
    newFileUrl = URL.createObjectURL(res.data);

    console.log('fetchFiles-srcUrl-------------------', fileType);
    // createImgPreview({
    //   imageList: [newFileUrl],
    //   defaultWidth: 700,
    //   rememberState: true,
    // });
    // return;
  } else {
    // turn on preview
    newFileUrl = fileUrl;
  }
  console.log('switch------------------------', newFileUrl);
  console.log(
    '`https://view.officeapps.live.com/op/view.aspx?src=${newFileUrl}`',
    `https://view.officeapps.live.com/op/view.aspx?src=${newFileUrl}`,
  );
  switch (fileType) {
    case 'word':
      window.open(`https://view.officeapps.live.com/op/view.aspx?src=${newFileUrl}`, '_blank');
      break;
    case 'excel':
      window.open(`https://view.officeapps.live.com/op/view.aspx?src=${newFileUrl}`, '_blank');
      break;
    case 'pdf':
      console.log('pdf', newFileUrl);
      window.open(newFileUrl, '_blank');
      break;
    case 'image':
      createImgPreview({
        imageList: [newFileUrl],
        defaultWidth: 700,
        rememberState: true,
      });
  }
  // console.log(record);
}

// 通过文件Url下载附件
export async function downloadFileByUrl({ fileUrl, fileName, authorization }) {
  try {
    let data = '';
    const { VITE_GLOB_SUB_DOMAIN } = getAppEnvConfig();
    // 把minio的域名换成img域名
    fileUrl = fileUrl.replace(`minio${VITE_GLOB_SUB_DOMAIN}`, `img${VITE_GLOB_SUB_DOMAIN}/MINIO`);
    // 判断是否需要授权才能下载的资源
    console.log('鉴权', authorization);

    if (authorization) {
      const token = getJti();
      console.log('fetchFiles-url', fileUrl);
      const res = await axios.get(`${fileUrl}?isAdmin=true`, {
        headers: {
          Authorization: `jti_${token}`,
        },
        responseType: 'blob',
      });
      data = res;
    } else {
      console.log('response');
      data = (await downloadFileApi(fileUrl)) as any;
    }
    if (data) {
      // download(data.file, data.fileName);
      // return true;
      const blobUrl = window.URL.createObjectURL(data.data);
      // 这里的文件名根据实际情况从响应头或者url里获取
      const a = document.createElement('a');
      a.href = blobUrl;
      a.download = fileName || data.fileName || data.name;
      a.click();
      window.URL.revokeObjectURL(blobUrl);

      // if (data) {
      //   var elink = document.createElement('a');
      //   elink.download = '导出表格.docx';
      //   elink.style.display = 'none';
      //   var blob = new Blob([data], { type: 'application/x-msdownload' });
      //   elink.href = URL.createObjectURL(blob);
      //   document.body.appendChild(elink);
      //   elink.click();
      //   document.body.removeChild(elink);
      // } else {
      //   // this.$message.error('导出异常请联系管理员');
      // }
    } else {
      createMessage.error('下载失败');
      return false;
    }
  } catch (error) {
    createMessage.error(error);
    return false;
  }
}

// 通过接口返回的字符串方法来格式化内容
export function formatContent(content: string, funcStr: string) {
  const func = new Function('return ' + funcStr.replace('obj', content));
  const text = func()();
  console.log('formatContent-1', content, funcStr);
  console.log('formatContent-2', text);
  return text;
}
